﻿using Serilog.Events;
using Serilog.Sinks.RichTextBox.Themes;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
using System.Windows.Forms;
using System.Windows.Threading;
using static System.Windows.Forms.LinkLabel;
using System.Threading;
using System.ServiceProcess;
using System.Collections.Concurrent;

namespace WatchDogApp.Windows
{
    /// <summary>
    /// LogWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LogWindow
    {
        private LogHandler logHandler;
        System.Timers.Timer _timer;
        public static ConcurrentQueue<string> Queue { get; } = new ConcurrentQueue<string>();

        public LogWindow()
        {
            InitializeComponent();

            //_timer = new System.Timers.Timer(1000) { AutoReset = true };
            //_timer.Elapsed += (sender, eventArgs) =>
            //{
            //    if (WatchDog.Serilog.ReceiveLogQueue.TryDequeue(out var s))
            //    {
            //        tryd
            //    }
            //};

            this.IsVisibleChanged += (o, e) =>
            {
                var newVal = (bool)e.NewValue;
                if (newVal)
                {
                   // _timer.Start();

                    logHandler = new LogHandler(() =>
                    {
                        ProcessMessages();
                    });
                }
                else
                {
                    //_timer.Stop();
                    logHandler?.Cancel();
                }
            };
        }


        StringBuilder stringBuilder = new StringBuilder();
        private void ProcessMessages()
        {

            if (WatchDog.Serilog.ReceiveLogQueue.Count > 0)
            {
                while (WatchDog.Serilog.ReceiveLogQueue.Count > 0)
                {
                    if (WatchDog.Serilog.ReceiveLogQueue.TryDequeue(out var ss))
                    {
                        stringBuilder.AppendLine(ss);
                    }

                }
            }
            if (stringBuilder.Length > 0)
            {
                this.Dispatcher.Invoke(() =>
                {
                    if (MyRichTextBox.Document.Blocks.Count > 1000)
                    {
                        MyRichTextBox.Document.Blocks.Clear(); // 清空文档的所有内容

                    }

                    
                    MyRichTextBox.AppendText(stringBuilder.ToString());
                    MyRichTextBox.ScrollToEnd();
                    stringBuilder.Clear();
                });
            }


        }

        //private async Task ProcessMessages()
        //{
        //    int msgCounter = 0;
        //    const string initial = $"<Paragraph xmlns =\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xml:space=\"preserve\">";

        //    StringBuilder sb = new(initial);

        //    async Task<string> ReadChannelAsync()
        //    {
        //        var logEvent = await _messageChannel.Reader.ReadAsync();
        //        StringWriter writer = new();
        //        _formatter.Format(logEvent, writer);
        //        return writer.ToString();
        //    }

        //    Task restartTimer() => Task.Delay(_minimumDelayForIncompleteBatch);

        //    var incompleteBatchTask = restartTimer();
        //    var logEventTask = ReadChannelAsync();

        //    while (true)
        //    {
        //        var firstTask = await Task.WhenAny(incompleteBatchTask, logEventTask);

        //        if (firstTask == logEventTask)
        //        {
        //            sb.Append(await logEventTask);
        //            msgCounter++;
        //            if (msgCounter < _batchSize)
        //            {
        //                logEventTask = ReadChannelAsync();
        //                continue;
        //            }
        //        }
        //        else if (msgCounter == 0)
        //        {
        //            //no messages, restart timer
        //            incompleteBatchTask = restartTimer();
        //            continue;
        //        }

        //        sb.Append("</Paragraph>");
        //        string xamlParagraphText = sb.ToString();
        //        await _richTextBox.BeginInvoke(_dispatcherPriority, _renderAction, xamlParagraphText);
        //        sb.Clear();
        //        sb.Append(initial);
        //        msgCounter = 0;
        //    }
        //}
    }

    public class LogHandler
    {
        private readonly CancellationTokenSource cts1 = new();
        private readonly CancellationToken token = new();
        public LogHandler(Action action)
        {
            token = cts1.Token;

            Task.Run(() =>
            {
                Task.Delay(1000);
                while (!token.IsCancellationRequested)
                {
                    action.Invoke();
                }
                IsCompleted = true;
            }, token);
        }

        public void Cancel()
        {
            cts1.Cancel();
        }

        public bool IsCompleted { get; private set; }
    }
}
